from exit import db
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime, date
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, SignatureExpired, BadSignature
import config
import shortuuid
import emoji


class User(db.Model):  # 用户表
    __tablename__ = 'c_user'
    id = db.Column(db.String(100), primary_key=True, default=shortuuid.uuid)
    # openid = db.Column(db.String(100))
    phone = db.Column(db.String(11))
    username = db.Column(db.String(50))
    nickname = db.Column(db.String(50))
    _password = db.Column(db.String(100))
    real_name = db.Column(db.String(50))
    avatar = db.Column(db.String(256))
    create_time = db.Column(db.DateTime, default=datetime.now)

    p_id = db.Column(db.String(100), index=True)  # 上级id
    p_id2 = db.Column(db.String(100), index=True)  # 上上级id
    rp_id = db.Column(db.String(100), index=True)   # 真实id
    p_path = db.Column(db.Text)     # 团队上级id

    blockade = db.Column(db.Integer, default=0)  # 状态  1为封号
    # real_status = db.Column(db.Integer, default=0)  # 状态  1审核  2成功  3驳回
    error_num = db.Column(db.Integer, default=5)    # 登录失败次数
    pay_pwd = db.Column(db.String(100), default='123456')  # 支付密码
    invite = db.Column(db.String(32))   # 邀请码

    n_level = db.Column(db.Integer, default=0, index=True)  # 级别
    n_level_manual = db.Column(db.Integer, default=0)  # 级别
    n_level_agent = db.Column(db.Integer, default=0)  # 级别

    team_num = db.Column(db.Integer, default=0)  # 团队人数
    direct_num = db.Column(db.Integer, default=0)  # 直推人数
    direct_buy = db.Column(db.Integer, default=0)  # 直推会员人数

    token = db.Column(db.String(100), default=shortuuid.uuid, index=True)  # token地址

    team_buy = db.Column(db.Integer, default=0)  # 团队购买数量
    user_buy = db.Column(db.Integer, default=0)  # 自己购买数量
    status = db.Column(db.Integer, default=0)  # 会员状态
    buy_num = db.Column(db.Integer, default=0)  # 购买次数

    income = db.Column(db.DECIMAL(20, 2), default=0)  # 收益
    income_r = db.Column(db.DECIMAL(20, 2), default=0)  # 保证金
    income_dj = db.Column(db.DECIMAL(20, 2), default=0)  # 冻结资金
    # income_s = db.Column(db.DECIMAL(20, 2), default=0)  # 扫码额度
    integral = db.Column(db.DECIMAL(20, 2), default=0)  # 积分
    sign_in_date = db.Column(db.Date)

    # reward_quota = db.Column(db.DECIMAL(20, 2), default=0)  # 烧伤
    openid = db.Column(db.String(100))
    id_card = db.Column(db.String(100))
    id_img = db.Column(db.String(100))
    sex = db.Column(db.Integer)
    deal_buy_num = db.Column(db.Integer, default=0)
    deal_sell_num = db.Column(db.Integer, default=0)
    open_status = db.Column(db.Integer, default=0)      # 开放点对点状态
    today_buy_num = db.Column(db.Integer, default=0)  # 买数量
    today_sell_num = db.Column(db.Integer, default=0)  # 卖数量
    deal_priority = db.Column(db.Integer, default=0)    # 购买权限
    other_income = db.Column(db.DECIMAL(20, 2), default=0)  # 购买权限
    other_status = db.Column(db.Integer, default=0)  # 购买权限
    total_deal_money = db.Column(db.DECIMAL(20, 2), default=0)  # 总成交额
    total_deal_buy_num = db.Column(db.Integer, default=0)  # 交易买总数量
    total_deal_sell_num = db.Column(db.Integer, default=0)  # 交易卖总数量

    def info_json(self):
        return {
            'id': self.id,
            'p_id': self.p_id,
            'username': emoji.emojize(self.username or ''),
            'nickname': emoji.emojize(self.username or ''),
            'real_name': self.real_name,
            'blockade': self.blockade,
            'phone': self.phone,
            'avatar': self.avatar,
            'user_buy': self.user_buy,
            'n_level': self.n_level,
            'invite': 'http://39.105.141.79/r/download',
            'invite_id': self.invite,
            'income': self.income,
            'income_r': self.income_r,
            'integral': self.integral,
            'status': self.status,
            'team_num': self.team_num,
            'id_card': self.id_card,
            'id_img': self.id_img,
            'sex': self.sex,
            'open_status': self.open_status,
            'deal_priority': self.deal_priority,
            'other_income': self.other_income,
            'other_status': self.other_status,
        }

    def team_json(self):
        return {
            'id': self.id,
            'username': emoji.emojize(self.username or ''),
            'nickname': emoji.emojize(self.username or ''),
            'phone': self.phone,
            'avatar': self.avatar,
            'team_buy': self.team_buy,
            'user_buy': self.user_buy,
            'status': self.status,
            'n_level': self.n_level,
        }

    def tree_json(self):
        return {
            'id': self.id,
            'name': emoji.emojize(self.username),
            'phone': self.phone,
            'p_id': self.p_id,
        }

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, new_pwd):
        self._password = generate_password_hash(new_pwd)

    def check_password(self, raw_pwd):
        return check_password_hash(self._password, raw_pwd)

    def generate_auth_token(self, expiration=31536000):
        s = Serializer(config.SECRET_KEY, expires_in=expiration)
        return s.dumps({'token': self.token})

    @staticmethod
    def verify_auth_token(token):
        s = Serializer(config.SECRET_KEY)
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None  # valid token, but expired
        except BadSignature:
            return None  # invalid token
        try:
            user = User.query.filter_by(token=data['token']).with_for_update().first()
            return user
        except Exception as e:
            print(e)
            db.session.close()
            return None

    @staticmethod
    def verify_auth_token_query(token):
        s = Serializer(config.SECRET_KEY)
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None  # valid token, but expired
        except BadSignature:
            return None  # invalid token
        try:
            user = User.query.filter_by(token=data['token']).first()
            return user
        except Exception as e:
            print(e)
            db.session.close()
            return None


class UserRecord(db.Model):  # 用户流水账单
    __tablename__ = 'c_user_record'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    create_time = db.Column(db.DateTime, default=datetime.now)
    user_id = db.Column(db.String(100), index=True)  # 用户id
    other_id = db.Column(db.String(100), index=True)
    num = db.Column(db.DECIMAL(20, 2))  # 数量
    r_state = db.Column(db.Integer)  # 1 加 2 减
    r_label = db.Column(db.Integer, index=True)     # 标签
    r_type = db.Column(db.Integer)      # 类型
    r_coin = db.Column(db.DECIMAL(20, 2))    # 潮通证
    r_wallet = db.Column(db.Integer)    # 钱包
    status = db.Column(db.Integer, default=0)    # 状态
    order_id = db.Column(db.String(100))    # 订单ID

    __table_args__ = (
        db.Index('user_id_r_label', 'user_id', 'r_label'),
    )

    def record_json(self):
        return {
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'num': self.num,
            'r_state': self.r_state,
            'r_coin': self.r_coin,
        }


class UserAddress(db.Model):    # 用户收货地址
    __tablename__ = 'c_user_address'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.String(32), index=True)
    create_time = db.Column(db.DateTime, default=datetime.now)
    status = db.Column(db.Integer, default=0, index=True)
    name = db.Column(db.String(32))  # 收货名字
    phone = db.Column(db.String(32))  # 收货手机号
    province = db.Column(db.String(255))  # 省
    city = db.Column(db.String(255))  # 市
    district = db.Column(db.String(255))  # 县(区)
    place = db.Column(db.String(255))  # 收货地址

    def address_json(self):
        return {
            'address_id': self.id,
            'status': self.status,
            'name': self.name,
            'phone': self.phone,
            'province': self.province,
            'city': self.city,
            'district': self.district,
            'place': self.place,
        }


class UserDevice(db.Model):     # 用户设备
    __tablename__ = 'c_user_device'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.String(100), nullable=False)
    device = db.Column(db.String(100))
    device_id = db.Column(db.String(100))
    device_name = db.Column(db.String(100))
    ip = db.Column(db.String(100))
    create_time = db.Column(db.DateTime, default=datetime.now)


class UserPayAccount(db.Model):     # 用户支付账户
    __tablename__ = 'c_user_pay_account'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    create_time = db.Column(db.DateTime, default=datetime.now)
    user_id = db.Column(db.String(100), index=True)
    pay_type = db.Column(db.Integer)        # 1alipay  2wechat  3pay_card
    pay_name = db.Column(db.String(255))
    pay_img = db.Column(db.String(255))
    pay_card = db.Column(db.String(50))
    real_name = db.Column(db.String(50))

    def pay_account_json(self):
        return {
            'pay_name': self.pay_name,
            'pay_type': self.pay_type,
            'pay_img': self.pay_img,
            'pay_card': self.pay_card,
            'real_name': self.real_name,
        }


class UserCollect(db.Model):    # 收藏
    __tablename__ = 'c_user_collect'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.String(32), index=True)
    create_time = db.Column(db.DateTime, default=datetime.now)
    update_time = db.Column(db.DateTime)
    status = db.Column(db.Integer, default=0)
    goods_id = db.Column(db.Integer, db.ForeignKey("c_mall_goods.id"))  # 商品skuId
    name = db.Column(db.String(50))
    goods_code = db.Column(db.String(100))

    goods = db.relationship("Goods")

    def user_collect_json(self):
        return {
            'collect_id': self.id,
            'status': self.status,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'goods_name': self.goods.name,
            'goods_code': self.goods_code,
            'name': self.name,
            # 'goods_img': self.goods.goods_img,
            'goods_id': self.goods.id,
        }

